﻿<MudForm Model="@PasswordModel" @ref="_passwordForm" Validation="@(Validator.ValidateValue(PasswordModel))"
         Style="display: flex; align-items: center; flex-direction: column;">
    <MudGrid Spacing="2" Justify="Justify.Center" Style="max-width:300px">
        <MudItem sm="12" xs="12">
            <MudTextField InputType="InputType.Password"
                          Label="@Localizer["Current Password"]"
                          For="@(() => PasswordModel.CurrentPassword)"
                          @bind-Value="PasswordModel.CurrentPassword"
                          Required="true" />
        </MudItem>
        <MudItem xs="12">
            <MudTextField InputType="InputType.Password"
                          Label="@Localizer["New Password"]"
                          For="@(() => PasswordModel.NewPassword)"
                          @bind-Value="PasswordModel.NewPassword"
                          Required="true" />
        </MudItem>
        <MudItem xs="12">
            <MudTextField InputType="InputType.Password"
                          Label="@Localizer["Confirm New Password"]"
                          For="@(() => PasswordModel.ConfirmPassword)"
                          @bind-Value="PasswordModel.ConfirmPassword"
                          Required="true" />
        </MudItem>
        <MudItem sm="12" xs="12" Class="d-flex justify-end">
            <MudButton ButtonType="ButtonType.Button" Color="Color.Primary" Class="ml-auto"
                       OnClick="@OnChangePasswordClick">
                @if (_submitting)
                {
                    <MudProgressCircular Class="ms-n1" Size="MudBlazor.Size.Small" Indeterminate="true" />
                    <MudText Class="ms-2">@ConstantString.Waiting </MudText>
                }
                else
                {
                    <MudText>@Localizer["Change Password"]</MudText>
                }
            </MudButton>
        </MudItem>
    </MudGrid>
</MudForm>

@code {
    public ChangePasswordModel PasswordModel { get; set; } = null!;
    [CascadingParameter] private UserProfile? UserProfile { get; set; }
    [Inject] public IStringLocalizer<CleanArchitecture.Blazor.Server.UI.Pages.Identity.Users.Profile> Localizer { get; set; } = null!;
    [Inject] public UserManager<ApplicationUser> UserManager { get; set; } = null!;

    private MudForm? _passwordForm;
    private bool _submitting;
    protected override Task OnInitializedAsync()
    {
        PasswordModel=new ChangePasswordModel
        {
            UserId   = UserProfile?.UserId ?? string.Empty,
            CurrentPassword = string.Empty,
            NewPassword = string.Empty,
            ConfirmPassword = string.Empty
        };
        return Task.CompletedTask;
    }
    public async Task<bool> ValidateAsync()
    {
        await _passwordForm!.Validate();
        return _passwordForm.IsValid;
    }

    private async Task OnChangePasswordClick()
    {
        await ChangePasswordAsync();
    }

    public async Task ChangePasswordAsync()
    {
        _submitting = true;
        try
        {
            await _passwordForm!.Validate();
            if (_passwordForm.IsValid)
            {
                var user = await UserManager.FindByIdAsync(PasswordModel.UserId);
                if (user == null)
                {
                    Snackbar.Add($"User [{PasswordModel.UserId}] not found.", Severity.Error);
                    return;
                }
                var result = await UserManager.ChangePasswordAsync(user, PasswordModel.CurrentPassword, PasswordModel.NewPassword);
                if (result.Succeeded)
                {
                    Snackbar.Add(Localizer["Password changed successfully"], Severity.Info);
                    // Clear the form
                    PasswordModel.CurrentPassword = string.Empty;
                    PasswordModel.NewPassword = string.Empty;
                    PasswordModel.ConfirmPassword = string.Empty;
                    StateHasChanged();
                }
                else
                {
                    Snackbar.Add(string.Join(",", result.Errors.Select(e => e.Description)), Severity.Error);
                }
            }
        }
        finally
        {
            _submitting = false;
        }
    }
}
